package com.msmall.community.tag;

import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.msmall.community.user.model.UserProfile;

/**
 *  生成<li><input type="checkbox" name="" value="" class="" checked="checked"/></li>
 *
 */
public class CheckboxFieldTag extends TagSupport {

	private static final long serialVersionUID = -131181397178917083L;

	private String type; // FAVSPORTS  FAVOTHERS

	private String name;
	
	private String selected; // 使用,分割的所有选项
	
	public int doStartTag() throws JspException {
		return (SKIP_BODY);
	}
	
	public int doEndTag() throws JspException {
		JspWriter writer = pageContext.getOut();
		StringBuffer buf = new StringBuffer();
		try{
			Map<String, String> map = null;
			if("FAVSPORTS".equalsIgnoreCase(type)){
				map = UserProfile.FAVSPORTS;
			}
			if("FAVOTHERS".equalsIgnoreCase(type)){
				map = UserProfile.FAVOTHERS;
			}
			if(map != null && !map.isEmpty()){
				for(Map.Entry<String, String> entry: map.entrySet()){
					String value = entry.getKey();
					String desc = entry.getValue();
					if(selected!=null && selected.indexOf(value) != -1){
						buf.append(getCheckbox(name, value, desc, true));
					}else{
						buf.append(getCheckbox(name, value, desc, false));
					}
				}
			}
			writer.print(buf.toString());
		}catch(Exception e){
			
		}
		return (SKIP_BODY);
	}
	//<li><input type="checkbox" name="" value="" checked="checked"/></li>
	private String getCheckbox(String name, String value, String message, boolean selected){
		StringBuffer buf = new StringBuffer();
		buf.append("<li>")
		.append("<input type=\"checkbox\" name=\"")
		.append(name)
		.append("\" value=\"")
		.append(value)
		.append("\"");
		if(selected){
			buf.append(" checked=\"checked\"");
		}
		buf.append("/>").append(message).append("</li>");
		return buf.toString();
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSelected() {
		return selected;
	}

	public void setSelected(String selected) {
		this.selected = selected;
	}
}
